package myServer.handler;

import component.timeConsumingTask.ExecuteTaskCollector;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import myServer.processor.ChatTransmitProcessor;
import myServer.session.ServerSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import protobuf.protoClass.ProtoMsg;

@ChannelHandler.Sharable
@Service("ChatRedirectHandler")
public class ChatTransmitHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    ChatTransmitProcessor chatTransmitProcessor;

    @Override
    public void channelRead(ChannelHandlerContext context, Object message) throws Exception {
        //判断消息实例
        if (!(message instanceof ProtoMsg.Message protoMessage)) {
            super.channelRead(context, message);
            return;
        }
        //判断消息类型
        ProtoMsg.HeadType headType = protoMessage.getType();
        if (!headType.equals(chatTransmitProcessor.type())) {
            super.channelRead(context, message);
            return;
        }
        //通过 Channel获取 ServerSession
        ServerSession serverSession = context.channel()
                .attr(ServerSession.SESSION_KEY)
                .get();
        //判断是否登录
        if (serverSession == null || !serverSession.isLogin()) {
            System.out.println("用户尚未登录，不能发送信息");
            return;
        }
        //异步执行发送操作
        ExecuteTaskCollector.add(() -> {
            chatTransmitProcessor.perform(serverSession, protoMessage);
        });
    }

}
